package fms.controller;

import fms.dao.Grib2InfoService;
import fms.model.Grib2WdInfo;
import fms.util.ConfUtil;
import fms.util.DateUtil;
import fms.util.SysConstants;
import org.apache.log4j.Logger;

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <P>FileName: Grib2DataParseController.java
 *
 * @param
 * @author LZJ
 *         <P>CreateTime: 2014-08-13
 *         <P>Description: 解析Grib2风温数据
 *         <P>Version: v1.0
 */
public class Grib2DataParseController implements IFlyPlanParseController {

    private Logger logger = Logger.getLogger(Grib2DataParseController.class);
    // 存入GRIB2_WD_INFO表的记录列表数据
    private ArrayList grib2InfoList = new ArrayList();
    // 提供数据库交互服务的对象
    private Grib2InfoService grib2InfoService = null;
    //线程池,设置固定10个线程
    ExecutorService pool = Executors.newFixedThreadPool(10);

    public Grib2DataParseController() {
        grib2InfoService = ConfUtil.getSingletonApplicationContextDao().getBean("grib2InfoService", Grib2InfoService.class);
    }

    @Override
    public boolean parseDataSource(File fDataSource) {
        BufferedReader bufReader = null;
        try {
            if (!fDataSource.exists() || fDataSource.isDirectory()) {
                throw new FileNotFoundException();
            }
            bufReader = new BufferedReader(new FileReader(fDataSource));
            String strLine = bufReader.readLine();
            int count = 0;
            while (null != strLine) {
                count++;
                if (count == 1) {
                    continue;
                }
                //正则表达式替换字符串中的 " 字符
                strLine = strLine.replaceAll("\"", "");
                //正则表达式替换字符串中的 空格+mb 字符
                strLine = strLine.replaceAll("\\smb", "");
                strLine = strLine.replaceAll("max wind", "0");
                strLine = strLine.replaceAll("tropopause", "0");
                Object[] obj = strLine.split(",");
                if (obj.length == 7) {
                    Grib2WdInfo grib2WdInfo = new Grib2WdInfo();
                    //开始时间
                    grib2WdInfo.setStartTime(DateUtil.StrToDate(obj[0].toString(), SysConstants.FORMAT_DATETIME_FULL));
                    //结束时间
                    grib2WdInfo.setEndTime(DateUtil.StrToDate(obj[1].toString(), SysConstants.FORMAT_DATETIME_FULL));
                    //风类型
                    grib2WdInfo.setWindType(obj[2].toString());
                    //大气压强
                    grib2WdInfo.setAtmosPressure(new BigInteger(obj[3].toString()));
                    //经度
                    grib2WdInfo.setLon(new BigDecimal(obj[4].toString()));
                    //纬度
                    grib2WdInfo.setLat(new BigDecimal(obj[5].toString()));
                    //风速
                    grib2WdInfo.setWindVel(new BigDecimal(obj[6].toString()));
                    //只要风类型为VGRD、UGRD、TMP并且大气压强不为max wind、tropopause（前面已经这两个）
                    if ((grib2WdInfo.getWindType().equals("VGRD")
                            || grib2WdInfo.getWindType().equals("UGRD")
                            || grib2WdInfo.getWindType().equals("TMP"))
                            && !grib2WdInfo.getAtmosPressure().toString().equals("0")) {
                        grib2InfoList.add(grib2WdInfo);
                    }
                } else {
                    logger.error("第" + count + "行数据错误:" + strLine);
                }
                strLine = bufReader.readLine();
                //每20000行 or 已经读到最后一行插入一次数据库，并清空grib2InfoList
                if (strLine == null || grib2InfoList.size() == 20000) {
                    ArrayList dataList = (ArrayList) grib2InfoList.clone();
                    grib2InfoList.clear();
                    SaveGrib2DataThread saveGrib2DataThread = new SaveGrib2DataThread(grib2InfoService, dataList);
                    pool.execute(saveGrib2DataThread);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        } finally {
            try {
                if (bufReader != null)
                    bufReader.close();
            } catch (IOException ex) {
                logger.error("流关闭失败");
                return false;
            }

        }
        return true;
    }

    @Override
    public boolean parseDataSource(String strDataSource) {
        return false;
    }

    @Override
    public void saveToDB() {

    }

    /**
     * 保存grib2数据线程
     */
    private static class SaveGrib2DataThread implements Runnable {
        private List list;
        private Grib2InfoService grib2InfoService;

        public SaveGrib2DataThread(Grib2InfoService grib2InfoService, List dataList) {
            this.grib2InfoService = grib2InfoService;
            this.list = dataList;
        }

        @Override
        public void run() {
            //保存grib2数据
            grib2InfoService.save(list);
            grib2InfoService.flush();
        }
    }
}
